//get params
$.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results)
    { 
        return 0; 
    }
    return results[1] || 0;
}

function seconds2time (seconds) {
    var hours   = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds - (hours * 3600)) / 60);
    var seconds = seconds - (hours * 3600) - (minutes * 60);
    var time = "";

    if (hours != 0) {
      time = hours+":";
    }
    if (minutes != 0 || time !== "") {
      minutes = (minutes < 10 && time !== "") ? "0"+minutes : String(minutes);
      time += minutes+":";
    }
    if (time === "") {
      time = seconds+"s";
    }
    else {
      time += (seconds < 10) ? "0"+seconds : String(seconds);
    }
    return time;
}


function modalMessage(title, msg){
	$("#dialog-message").attr("title",title);
	$("#dialog-message .alertMsg").text(msg);
	$("#dialog-message").dialog({
			modal: true,
			buttons: {
				Ok: function() {
					$( this ).dialog( "close" );
				}
			}
	});
	
}

var MAINVIDEO = {
		init: function(videoId){
			if(videoId==undefined || videoId==0){
				throw{ name: "Error", message: "Id param in url is empty. Please enter a valid youtube video id."}
			}else{
				MAINVIDEO.getVideoInfo(videoId);
			}
		},
		getVideoPlayer: function(videoId){
			$("#videoPlayer").text("You need Flash player 8+ and JavaScript enabled to view this video.");
			
			var params = { allowScriptAccess: "always" };
			var atts = { id: "myytplayer" };
			swfobject.embedSWF("http://www.youtube.com/v/"+videoId+"?enablejsapi=1&playerapiid=ytplayer&version=3",
							   "videoPlayer", "640", "360", "8", null, null, params, atts);	
		},
		getVideoInfo: function(videoId){
			$.ajax({
			  url: "http://gdata.youtube.com/feeds/api/videos/"+videoId+"?v=2&alt=jsonc",
			  dataType: 'jsonp',
			  type:'POST',
			  cache:false,
			  success: function (data) { 
				if('error' in data){
						modalMessage("Request Error",data.error.message);
					}else{
						MAINVIDEO.getVideoPlayer(videoId);
						MAINVIDEO.showVideoInfo(data);
				}
			  }
			});
		},
		showVideoInfo: function(videoInfo){
			$("#header h1").html(videoInfo.data.title);
			$("#videoDesc").html(videoInfo.data.description);
			$("#videoViews").html(videoInfo.data.viewCount+" Views");
			//$("#videoDuration").html(seconds2time(videoInfo.data.duration));
			$('#videoDate').prepend("Posted "+Date.create('2009-10-25T08:40:23.000Z').format('{Weekday} {Month} {ord}, {year}')+"&nbsp;");
			$("#postedBy").html("by "+videoInfo.data.uploader);
		}
}
	
var RELATEDVIDEOS = {
		init: function(videoId){
			if(videoId==undefined || videoId==0){
				throw{ name: "Error", message: "Id param in url is empty. Please enter a valid youtube video id."}
			}else{
				RELATEDVIDEOS.getRelatedVideos(videoId);
			}
		},
		getRelatedVideos: function(videoId){
			$.ajax({
				  url: "http://gdata.youtube.com/feeds/api/videos/"+videoId+"/related?v=2&alt=jsonc&max-results="+APPCONF.relatedVideosMax,
				  dataType: 'jsonp',
				  type:'POST',
				  cache:false,
				  success: function (data) {
					if('error' in data){
						modalMessage("Request Error",data.error.message);
					}else{
						RELATEDVIDEOS.showRelatedVideos(data);
					}
				  }
				});
		},
		showRelatedVideos: function(videos){
			$.each(videos.data.items, function(i, val) {
			   var content = "<div class=\"videoItem\"><div class=\"borderDiv\"><div class=\"thumbImg\" style=\"background: url("+val.thumbnail.sqDefault+") center center\"><div class=\"relTime\">"+seconds2time(val.duration)+"</div><div class=\"addToList\">+</div></div></div><div class=\"itemContent\"><h3>"+val.title.truncate(20, '...', false)+"</h3><span>"+val.viewCount+" Views</span></div></div>";
			   
			   $("#relatedVideos").append(content);
			});
		
			$('#relatedVideos').on('hover','div.videoItem', function( event ) {
				$(this).toggleClass("bgSelected");
			});
		}
}	